import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_yres/model/shop/tbcate_model.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_yres/model/banner_model.dart';
import 'package:flutter_yres/model/shop/tbactivity_model.dart';
import 'package:flutter_yres/pages/shop/shop_sub_page.dart';
import 'package:flutter_yres/model/shop/hdk_list_model.dart';
import 'package:flutter_yres/pages/shop/shop_detail_page.dart';
import 'package:flutter_yres/pages/shop/SearchGoods.dart';
import 'package:flutter_yres/pages/shop/wuliao_page.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import '../pages/shop/hdk_page.dart';
import '../pages/shop/jd_page.dart';
import '../pages/shop/newPdd.dart';
class ShopPage extends StatefulWidget {
  @override
  _ShopPageState createState() => _ShopPageState();
}

class _ShopPageState extends State<ShopPage> {
  double windowstateHeight =
      MediaQueryData.fromWindow(window).padding.top; //状态栏
  double bannerHeight = ScreenUtil.getInstance().setWidth(750) * 0.4;
  TabController _tabController;
  List<CateModelData> tabs = []; //淘宝顶级分类数组
  List subs = [
    {'name': '淘宝', 'image': 'images/icon_menu_taobao.png'},
    {'name': '天猫', 'image': 'images/ticon_tainmao.png'},
    {'name': '京东', 'image': 'images/ticon_jingdong.png'},
    {'name': '苏宁', 'image': 'images/ticon_suning.png'},
    {'name': '拼多多', 'image': 'images/icon_menu_pingduoduo.png'}
  ]; //
  List<BannerModelData> bannerData = []; //轮播图数组
  List<ActivityModelData> activityData = new List(); //淘宝推广活动数组
  List<HDKListModelData> shopData = []; //商品数组
  EasyRefreshController _controller = new EasyRefreshController();
  var min_id = 1; //分页
  @override
  Widget build(BuildContext context) {

    return new DefaultTabController(
      length: tabs.length,
      child: new Scaffold(
        appBar: new AppBar(
          title: _buildSearch(),
          bottom: new TabBar(
            isScrollable: true,
            tabs: tabs.map((item) {
              return _tabsBuilder(context, item);
            }).toList(),
            controller: _tabController,
            onTap: (index) {
              print(tabs[index].taobao_cat_id);
              // setState(() {
              //   getTBSubCatList(tabs[index].pid);
              // });
            },
          ),
        ),
        body: new TabBarView(
          children: tabs.map<Widget>((item) {
            if (item.name == '全部商品') {
              return _buildHome(context, item);
            } else {
              // return _buildSub(context, item);
              return new ShopSubPage(taobao_cat_id: item.taobao_cat_id);
            }
          }).toList(),
        ),
      ),
    );
  }

  Widget _tabsBuilder(BuildContext context, item) {
    return Tab(text: item.name);
  }

  //搜索组件
  _buildSearch() {
    return new Container(
      child: Row(
        children: <Widget>[
          Expanded(
            child: Container(
              height: ScreenUtil.getInstance().setHeight(DP_80),
              child: Center(
                child: new GestureDetector(
                  child: Container(
                    padding: EdgeInsets.fromLTRB(
                        ScreenUtil.getInstance().setHeight(DP_20),
                        ScreenUtil.getInstance().setWidth(DP_10),
                        ScreenUtil.getInstance().setHeight(DP_20),
                        ScreenUtil.getInstance().setWidth(DP_10)),
                    margin: EdgeInsets.fromLTRB(
                        ScreenUtil.getInstance().setHeight(DP_30),
                        0,
                        ScreenUtil.getInstance().setHeight(DP_20),
                        0),
                    decoration: BoxDecoration(
                        color: Color.fromARGB(120, 255, 255, 255),
                        borderRadius: BorderRadius.circular(25.0)),
                    child: new Row(
                      children: <Widget>[
                        Icon(
                          Icons.search,
                          size: 25,
                          color: Colors.white,
                        ),
                        Text(
                          '搜索商品、品牌',
                          style: TextStyle(color: Colors.white, fontSize: 14),
                        )
                      ],
                    ),
                  ),
                  onTap: () {
                    Navigator.of(context)
                        .push(new MaterialPageRoute(builder: (context) {
                      return new SearchGoodsPage(type: '1');
                    }));
                  },
                ),
              ),
            ),
          ),
        ],
      ),
      width: double.maxFinite,
      // height: kBottomNavigationBarHeight + 40,
      margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
      color: kDefaultColor,
      // padding: EdgeInsets.fromLTRB(20, windowstateHeight, 20, 8),
    );
  }

  //商品cell
  getItemContainer(BuildContext context, int index) {
    HDKListModelData model = shopData[index];
    var price = RichText(
      textAlign: TextAlign.left,
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(text: '¥', style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(24))),
        TextSpan(text: model.itemendprice, style: TextStyle(fontSize:ScreenUtil.getInstance().setSp(34))),
        TextSpan(
          text: model.itemprice,
          style: TextStyle(
              fontSize: ScreenUtil.getInstance().setSp(24),
              color: Colors.grey,
              decoration: TextDecoration.lineThrough,
              decorationColor: Colors.grey),
        ),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    var quanHeader = Container(
      width: ScreenUtil.getInstance().setWidth(40),
      height: ScreenUtil.getInstance().setWidth(34),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("images/item_youhuiquan_header.png"),
          fit: BoxFit.cover,
        ),
      ),
    );
    var quan = Container(
      width: ScreenUtil.getInstance().setWidth(70),
      height: ScreenUtil.getInstance().setWidth(34),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("images/item_youhuiquan_footer.png"),
          fit: BoxFit.cover,
        ),
      ),
      child: Center(
          child: Text(
        model.couponmoney + '元',
        style: TextStyle(color: Colors.white, fontSize: ScreenUtil.getInstance().setSp(24)),
      )),
    );
    var yongjin = Container(
      margin: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(20), 0, ScreenUtil.getInstance().setWidth(20), 0),
      height: ScreenUtil.getInstance().setWidth(34),
      color: Color.fromRGBO(250, 226, 226, 1),
      child: Center(
          child: Text('预估赚¥' + formatNum(double.parse(model.tkrates)/100*double.parse(model.itemendprice),2).toString()  ,
              style: TextStyle(color: Colors.red, fontSize: ScreenUtil.getInstance().setSp(20)))),
    );
    return GestureDetector(
      child: Container(
          color: Colors.white,
          margin: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(10), 0, ScreenUtil.getInstance().setWidth(10), 0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              CachedNetworkImage(
                fit: BoxFit.fill,
                imageUrl: model.itempic,
                width: (ScreenUtil.getInstance().setWidth(750) - ScreenUtil.getInstance().setWidth(20)) / 2,
                height: (ScreenUtil.getInstance().setWidth(750) - ScreenUtil.getInstance().setWidth(20)) / 2,
                placeholder: (context, url) => Image.asset(
                  'images/pic_default.png',
                  fit: BoxFit.fill,
                  width: (ScreenUtil.getInstance().setWidth(750) - ScreenUtil.getInstance().setWidth(20)) / 2,
                  height: (ScreenUtil.getInstance().setWidth(750) - ScreenUtil.getInstance().setWidth(20)) / 2,
                ),
                errorWidget: (context, url, error) => Image.asset(
                  'images/pic_default.png',
                  fit: BoxFit.fill,
                  width: (ScreenUtil.getInstance().setWidth(750) - ScreenUtil.getInstance().setWidth(20)) / 2,
                  height: (ScreenUtil.getInstance().setWidth(750) - ScreenUtil.getInstance().setWidth(20)) / 2,
                ),
              ),
              Text(model.itemtitle, maxLines: 2, style: TextStyle(fontSize:ScreenUtil.getInstance().setSp(26))),
              Container(
                margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(5)),
                child: price,
              ),
              Container(
                margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(5)),
                child: Text('已售' + model.itemsale,
                    style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(24), color: Colors.grey)),
              ),
              Container(
                margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(5)),
                child: Row(
                  children: <Widget>[
                    Expanded(
                      flex: 1,
                      child: Row(
                        children: <Widget>[quanHeader,Expanded(
                          child:quan
                        ) ],
                      ),
                    ),
                    Expanded(flex: 2, child: yongjin)
                  ],
                ),
              )
            ],
          )),
      onTap: () {
        Navigator.push(
            context,
            MaterialPageRoute(
                //导航打开新视图
                builder: (context) =>
                    ShopDetailPage(hdkmodel: model) //打开第二个页面，并传值，传递值的名称是model
                ));
      },
    );
  }

      String formatNum(double num, int postion) {
    if ((num.toString().length - num.toString().lastIndexOf(".") - 1) <
        postion) {
      //小数点后有几位小数
      return (num.toStringAsFixed(postion)
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString());
    } else {
      return (num.toString()
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString());
    }
  }

/*首页****************************************************/
//轮播图组件
  _buildBanner() {
    return new Container(
      width: ScreenUtil.getInstance().setWidth(750),
      height: bannerHeight,
      child: Swiper(
        itemBuilder: _swiperBuilder,
        itemCount: bannerData.length,
        loop: false,
        autoplay: true,
        autoplayDelay: 15000,
        pagination: new SwiperPagination(
            builder: DotSwiperPaginationBuilder(
          color: Colors.black54,
          activeColor: Colors.white,
        )),
        scrollDirection: Axis.horizontal,
        onTap: (index) {
          //点击轮播图事件
        },
      ),
    );
  }

  Widget _swiperBuilder(BuildContext context, int index) {
    return CachedNetworkImage(
       width: ScreenUtil.getInstance().setWidth(750),
      height: bannerHeight,
      fit: BoxFit.fill,
      imageUrl: Api.BaseUrl + bannerData[index].img,
      placeholder: (context, url) => Image.asset(
        'images/pic_default.png',
        fit: BoxFit.fill,
         width: ScreenUtil.getInstance().setWidth(750),
      height: bannerHeight,
      ),
      errorWidget: (context, url, error) => Image.asset(
        'images/pic_default.png',
        fit: BoxFit.fill,
         width: ScreenUtil.getInstance().setWidth(750),
      height: bannerHeight,
      ),
    );
  }

/*圆形item image+text */
  Widget _itemBuilder(BuildContext context, item) {
    return InkWell(
        onTap: () {
          print(item['name']);
          if (item['name'] == '拼多多') {
            // Navigator.of(context).pushNamed("pdd");
            Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return new NewPddPage();
          }));
          }
          if (item['name'] == '淘宝') {
            Navigator.of(context).pushNamed("tbCate");
          }

          if (item['name'] == '天猫') {
 Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return new HDKPage(type: '9', name:'天猫');
          }));
          }
          if (item['name'] == '苏宁') {
 Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return new HDKPage(type: '4', name:'苏宁');
          }));
          }
          if (item['name'] == '京东') {
//  Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
//             return new JDPage();
//           }));
 Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return new HDKPage(type: '7', name:'京东');
          }));
          }
        },
        child: Column(
          children: <Widget>[
            Container(
              // height: kMargin20,
              // color: Colors.yellow,
              padding: EdgeInsets.fromLTRB(0, ScreenUtil.getInstance().setWidth(10), 0, 0),
              child:
                  Image.asset(item['image'], width: ScreenUtil.getInstance().setWidth(90)),
            ),
            Text(item['name'], style: TextStyle(fontSize:ScreenUtil.getInstance().setSp(26))),
          ],
        ));
  }

//全部商品主页内容
  _buildHome(BuildContext context, item) {
    return Container(
      child: new EasyRefresh(
        //刷新  加载组件
        controller: _controller,
          enableControlFinishRefresh: true,
              enableControlFinishLoad: true,
        header: MaterialHeader(),
              footer: MaterialFooter(),
        child: CustomScrollView(slivers: <Widget>[
          SliverToBoxAdapter(
            child: Container(
                height: bannerHeight,
                child: Column(
                  children: <Widget>[_buildBanner()],
                )),
          ),
          SliverGrid(
            gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
              maxCrossAxisExtent: (ScreenUtil.getInstance().setWidth(750) - ScreenUtil.getInstance().setWidth(20)) / 4,
              mainAxisSpacing: 0.0,
              crossAxisSpacing: 0.0,
              childAspectRatio: 1, //子控件宽高比
            ),
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return _itemBuilder(context, subs[index]);
              },
              childCount: subs.length,
            ),
          ),
          // SliverToBoxAdapter(
          //   child: Container(
          //     margin: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(15), ScreenUtil.getInstance().setWidth(15), ScreenUtil.getInstance().setWidth(15), 0),
          //     child:
          //         Image.asset('images/list_bg_wps.png', fit: BoxFit.fitWidth),
          //   ),
          // ),
          SliverGrid(
            gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
              maxCrossAxisExtent: (ScreenUtil.getInstance().setWidth(750) - ScreenUtil.getInstance().setWidth(10)) / 2,
              mainAxisSpacing: ScreenUtil.getInstance().setWidth(10),
              crossAxisSpacing: ScreenUtil.getInstance().setWidth(10),
              childAspectRatio: 2.0, //子控件宽高比
            ),
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return GestureDetector(
                  child: CachedNetworkImage(
                    fit: BoxFit.fill,
                    imageUrl: Api.BaseUrl + activityData[index].icon,
                    placeholder: (context, url) => Image.asset(
                      'images/pic_default.png',
                      fit: BoxFit.fill,
                    ),
                    errorWidget: (context, url, error) => Image.asset(
                      'images/pic_default.png',
                      fit: BoxFit.fill,
                    ),
                  ),
                  onTap: () {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            //导航打开新视图
                            builder: (context) => WuLiaoPage(
                                material_id: activityData[index].tb_activity_id,
                                title: activityData[index]
                                    .taobao_activity_name) //打开第二个页面，并传值，传递值的名称是model
                            ));
                  },
                );
              },
              childCount: activityData.length,
            ),
          ),
          SliverToBoxAdapter(
            child: Container(
              margin: EdgeInsets.fromLTRB(0, ScreenUtil.getInstance().setWidth(15), 0, 0),
              child: Image.asset('images/icon_hot.png', fit: BoxFit.fitWidth),
            ),
          ),
          SliverGrid(
            gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
              maxCrossAxisExtent: (ScreenUtil.getInstance().setWidth(750) - ScreenUtil.getInstance().setWidth(10) * 2) / 2,
              mainAxisSpacing: 10.0,
              crossAxisSpacing: 15.0,
              childAspectRatio: 0.6, //子控件宽高比
            ),
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return getItemContainer(context, index);
              },
              childCount: shopData.length,
            ),
          ),
        ]),
        onRefresh: () async {
          getTBTopCatList();
          getBannerList('1'); //轮播
          getActivity();
          min_id = 1;
          getHDKGoodsListUrl();
        },
        onLoad: () async {
          getHDKGoodsListUrl();
        },
      ),
    );
  }

/*控制器**************************************************************/
  @override
  void initState() {
    getTBTopCatList();
    getBannerList('1'); //轮播
    getActivity();
    getHDKGoodsListUrl();
    super.initState();
  }

/*网络请求**************************************************************/
/*轮播图*/
  getBannerList(String Cat_id) async {
    FormData data = new FormData.fromMap({'cat_id': Cat_id});
    Response<String> response =
        await HttpUtil().post(Api.GetBannerListUrl, data: data);
    Map userMap = json.decode(response.data);
    BannerModelEntity bannerEntity = new BannerModelEntity.fromJson(userMap);
    if (bannerEntity.code == 1) {
      if (mounted) {
        setState(() {
          //顶部轮播
          bannerData.clear();
          bannerData = bannerEntity.data;
        });
      }
    }
  }

  /*获取淘宝推广活动列表 */
  getActivity() async {
    FormData data = new FormData.fromMap({});
    Response<String> response =
        await HttpUtil().post(Api.GetTBActivityUrl, data: data);
    Map userMap = json.decode(response.data);
    // print(userMap);
    ActivityModelEntity entity = new ActivityModelEntity.fromJson(userMap);
    if (entity.code == 1) {
      if (mounted) {
        setState(() {
          activityData.clear();
          activityData.addAll(entity.data);
        });
      }
    }
  }

  /*淘宝顶级列表*/
  getTBTopCatList() async {
    FormData data = new FormData.fromMap({});
    Response<String> response =
        await HttpUtil().post(Api.GetTBTopCatListUrl, data: data);
    Map userMap = json.decode(response.data);
    CateModelEntity itemEntity = new CateModelEntity.fromJson(userMap);
    if (itemEntity.code == 1) {
      if (mounted) {
        var json = {
          'taobao_cat_id': '0000',
          'name': '全部商品',
          'icon': '',
          'pid': '0000',
        };
        CateModelData first = CateModelData.fromJson(json);
        setState(() {
          tabs.clear();
          tabs = itemEntity.data;
          tabs.insert(0, first);
        });
      }
    }
  }

  /*好单库商品筛选*/
  getHDKGoodsListUrl() async {
    FormData data = new FormData.fromMap(
        {'type': '1', 'cid': '15', 'back': '10', 'min_id': min_id});
    Response<String> response =
        await HttpUtil().post(Api.GetHDKGoodsListUrl, data: data);
    Map userMap = json.decode(response.data);
    // print(userMap);
    HDKListModelEntity itemEntity = new HDKListModelEntity.fromJson(userMap);
    if (itemEntity.code == 1) {
      if (mounted) {
        setState(() {
          if (min_id == 1) {
            shopData.clear();
            shopData = itemEntity.data;
            min_id = itemEntity.min_id;
            _controller.finishRefresh();
            // print(min_id);
          } else {
            min_id = itemEntity.min_id;
            shopData.addAll(itemEntity.data);
            _controller.finishLoad();
          }
        });
      }
    }
  }
}
